package com.smartwasser.yunhtgl.apphtgl.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.listener.DialogUIListener;
import com.smartwasser.yunhtgl.apphtgl.App;
import com.smartwasser.yunhtgl.apphtgl.R;
import com.smartwasser.yunhtgl.apphtgl.adapter.CaseAdapter01;
import com.smartwasser.yunhtgl.apphtgl.base.BaseActivity;
import com.smartwasser.yunhtgl.apphtgl.base.BaseConstant;
import com.smartwasser.yunhtgl.apphtgl.base.BaseSpinner;
import com.smartwasser.yunhtgl.apphtgl.bean.CaseProcess1Bean;
import com.smartwasser.yunhtgl.apphtgl.bean.CaseProcess1Bean.ListBean;
import com.smartwasser.yunhtgl.apphtgl.bean.CompanyBean;
import com.smartwasser.yunhtgl.apphtgl.presenter.CaseProcess1Presenter;
import com.smartwasser.yunhtgl.apphtgl.presenter.CaseProcess1PresenterImpl;
import com.smartwasser.yunhtgl.apphtgl.tree.Dept;
import com.smartwasser.yunhtgl.apphtgl.tree.Node;
import com.smartwasser.yunhtgl.apphtgl.tree.NodeHelper;
import com.smartwasser.yunhtgl.apphtgl.tree.NodeTreeAdapter;
import com.smartwasser.yunhtgl.apphtgl.view.CaseProcess1View;
import com.smartwasser.yunhtgl.apphtgl.utils.ACache;
import com.smartwasser.yunhtgl.apphtgl.utils.Logger;
import com.smartwasser.yunhtgl.apphtgl.widget.RefreshLayout;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.view.View.inflate;
import static com.dou361.dialogui.DialogUIUtils.dismiss;
import static com.smartwasser.yunhtgl.apphtgl.R.id.case_censor_check;
import static com.smartwasser.yunhtgl.apphtgl.R.id.case_censor_feed;
import static com.smartwasser.yunhtgl.apphtgl.base.BaseConstant.startSH;
import static com.smartwasser.yunhtgl.apphtgl.base.BaseConstant.successSPGreat1SH;
import static com.smartwasser.yunhtgl.apphtgl.utils.SharedUtils.getStringData;

/**
 * 待完成合同备案
 */
public class CaseProcess1 extends BaseActivity implements CaseProcess1View {
    private CaseProcess1Presenter caseProcess1Presenter = new CaseProcess1PresenterImpl(this);
    private List<ListBean> mList = new ArrayList<>();
    private Boolean getCom = false, getMessage = false;
    private Handler mHandler = new Handler();
    private String currentId;
    private CompanyBean companyBean;
    private Dialog loadingHorizontal, MdAlert;
    private CaseAdapter01 mAdapter;
    private String year = "2018", season = "";
    private ACache aCache;
    @BindView(R.id.tv_toolbar)
    TextView tv_toolbar;
    @BindView(R.id.toolbar_what)
    TextView toolbar_what;
    @BindView(R.id.swipeRefresh)
    RefreshLayout swipeRefresh;
    @BindView(R.id.sp_list)
    ListView sp_list;
    @BindView(R.id.checkbox_visibility)
    LinearLayout checkbox_visibility;
    @BindView(R.id.checkbox_all)
    CheckBox checkbox_all;
    @BindView(R.id.all_com)
    LinearLayout all_com;
    @BindView(R.id.finish1)
    TextView finish1;
    @BindView(R.id.finish2)
    Spinner finish2;
    @BindView(R.id.finish3)
    Spinner finish3;

    String ids="";

    @Override
    public void setContentLayout() {
        setContentView(R.layout.activity_case_process1);
        ButterKnife.bind(this);
        aCache = ACache.get(this);
    }

    @Override
    public void initView() {
        tv_toolbar.setText("待完成合同备案");
        toolbar_what.setText("编辑");
        toolbar_what.setVisibility(View.VISIBLE);
        initSpinner();
        initRecyclerView();
    }

    @Override
    public void initData() {
        loadingHorizontal = showLoadingHorizontal(this, "加载中...").show();
        try {
            caseProcess1Presenter.getMessages(getStringData(this, "JSESSIONID", ""), year, season, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != aCache.getAsObject("mLinkedList")) {
            Logger.e("有缓存，读取缓存");
            getCom = true;
            mLinkedList = (LinkedList<Node>) aCache.getAsObject("mLinkedList");
        } else {
            Logger.e("没有缓存，请求网络");
            try {
                caseProcess1Presenter.getCompany(getStringData(this, "JSESSIONID", ""));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @OnClick({R.id.back, R.id.checkbox_all_layout, R.id.toolbar_right, R.id.checkbox_commit, R.id.all_com})
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.toolbar_right:
                if (null != mList && mList.size() > 0) {
                    if (toolbar_what.getText().equals("编辑")) {
                        toolbar_what.setText("取消");
                        checkbox_visibility.setVisibility(View.VISIBLE);
                        mAdapter.chechVisibity(true);
                        mAdapter.notifyDataSetChanged();
                    } else {
                        toolbar_what.setText("编辑");
                        checkbox_visibility.setVisibility(View.GONE);
                        App.getInstance().getCaseProcess1List().clear();
                        mAdapter.chechVisibity(false);
                        checkbox_all.setChecked(false);
                        mAdapter.checkAll(false);
                        mAdapter.notifyDataSetChanged();
                    }
                } else {
                    showResult("当前无数据");
                }
                break;
            case R.id.checkbox_commit:
                showCommit(App.getInstance().getCaseProcess1List().toString());
                break;
            case R.id.checkbox_all_layout:
                if (!checkbox_all.isChecked()) {
                    checkbox_all.setChecked(true);
                    mAdapter.checkAll(true);
                    mAdapter.notifyDataSetChanged();
                } else {
                    App.getInstance().getCaseProcess1List().clear();
                    checkbox_all.setChecked(false);
                    mAdapter.checkAll(false);
                    mAdapter.notifyDataSetChanged();
                }
                break;
            case R.id.all_com:
                showPopupWindow(all_com);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Logger.e("onActivityResult");
        if (requestCode == startSH) {
            switch (resultCode) {
                case successSPGreat1SH:
                    Logger.e("successSPGreat1SH");
                    if (null != mList && mList.size() > 0) {
                        mList.clear();
                        App.getInstance().getCaseProcess1List().clear();
                        mAdapter.refresh(mList);
                    }
                    loadingHorizontal = showLoadingHorizontal(this, "正在加载...").show();
                    getMessagesData(currentId);
                    break;
            }
        }
    }

    private void getMessagesData(String com) {

        try {
            Logger.e("JSESSIONID = " + getStringData(this, "JSESSIONID", ""));
            Logger.e("year = " + year);
            Logger.e("season = " + season);
            Logger.e("com = " + com);
            caseProcess1Presenter.getMessages(getStringData(this, "JSESSIONID", ""), year, season, com);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void success(CaseProcess1Bean caseProcessBean) {
        if (!getMessage) {
            getMessage = true;
        }
        if (getMessage && getCom && loadingHorizontal.isShowing()) {
            dismiss(loadingHorizontal);
        }
        if (swipeRefresh.isRefreshing()) {
            swipeRefresh.setRefreshing(false);
        }
        this.mList = caseProcessBean.getList();
        mAdapter.refresh(mList);
    }

    @Override
    public void successCompany(CompanyBean companyBean) {
        this.companyBean = companyBean;
        new Thread() {
            @Override
            public void run() {
                Logger.e("successCompany");
                data = new ArrayList<>();
                addOne(data);
                mLinkedList.addAll(NodeHelper.sortNodes(data));

                if (!getCom) {
                    getCom = true;
                }
                aCache.put("mLinkedList", mLinkedList, BaseConstant.TIME_HOUR);
                if (getMessage && getCom && loadingHorizontal.isShowing()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismiss(loadingHorizontal);
                        }
                    });
                }
            }
        }.start();
    }

    @Override
    public void error() {
        dismiss(loadingHorizontal);
        showError();
    }

    @Override
    public void successSH() {
        dismiss(loadingHorizontal);
        showResult("审核成功");

        toolbar_what.setText("编辑");
        checkbox_visibility.setVisibility(View.GONE);
        App.getInstance().getCaseProcess1List().clear();
        mAdapter.chechVisibity(false);
        checkbox_all.setChecked(false);
        mAdapter.checkAll(false);
        mAdapter.notifyDataSetChanged();
        if (null != mList && mList.size() > 0) {
            mList.clear();
            App.getInstance().getCaseProcess1List().clear();
            mAdapter.refresh(mList);
        }
        loadingHorizontal = showLoadingHorizontal(this, "正在加载...").show();
        getMessagesData(currentId);
    }

    @Override
    public void errorSH() {
        dismiss(loadingHorizontal);
        showResult("审核失败");
    }

    private void initRecyclerView() {
        mAdapter = new CaseAdapter01(this, mList);
        sp_list.setAdapter(mAdapter);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (null != mList && mList.size() > 0) {
                            mList.clear();
                            App.getInstance().getCaseProcess1List().clear();
                            mAdapter.refresh(mList);
                        }
                        Logger.e("id = " + currentId);
                        if (null != currentId && !currentId.trim().isEmpty() && !currentId.equals("全部单位")) {
                            getMessagesData(currentId);
                        } else {
                            getMessagesData(null);
                        }
                    }
                }, 500);
            }
        });
        mAdapter.setOnCheckListener(new CaseAdapter01.OnItemCheckListener() {
            @Override
            public void onItemcheck(int position) {
                if (checkbox_all.isChecked()) {
                    checkbox_all.setChecked(false);
                    mAdapter.checkAll(false);
                }
                mAdapter.notifyDataSetChanged();
            }
        });
        sp_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Intent intent = new Intent(CaseProcess1.this, CaseCensorActivity.class);
                intent.putExtra("type", "unFinish");
                intent.putExtra("id", mList.get(position).getId());
                startActivityForResult(intent, startSH);
            }
        });
    }


    private void initSpinner() {
        final List<String> arrayList2 = new ArrayList<>();
        arrayList2.add("2018");
        arrayList2.add("2017");
        arrayList2.add("2016");
        final List<String> arrayList3 = new ArrayList<>();
        arrayList3.add("全部月度");
        arrayList3.add("第1月度");
        arrayList3.add("第2月度");
        arrayList3.add("第3月度");
        arrayList3.add("第4月度");
        arrayList3.add("第5月度");
        arrayList3.add("第6月度");
        arrayList3.add("第7月度");
        arrayList3.add("第8月度");
        arrayList3.add("第9月度");
        arrayList3.add("第10月度");
        arrayList3.add("第11月度");
        arrayList3.add("第12月度");
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
                R.layout.spinner_drop, arrayList2) {
            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View view = inflate(getContext(), R.layout.spinner_item_layout, null);
                TextView label = view.findViewById(R.id.spinner_item_label);
                label.setText(arrayList2.get(position));
                if (finish2.getSelectedItemPosition() == position) {
                    label.setTextColor(getResources().getColor(R.color.colorTitle));
                } else {
                    label.setTextColor(getResources().getColor(R.color.colorText));
                }
                return view;
            }

        };
        ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(this,
                R.layout.spinner_drop, arrayList3) {

            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View view = inflate(getContext(), R.layout.spinner_item_layout, null);
                TextView label = view.findViewById(R.id.spinner_item_label);
                label.setText(arrayList3.get(position));
                if (finish3.getSelectedItemPosition() == position) {
                    label.setTextColor(getResources().getColor(R.color.colorTitle));
                } else {
                    label.setTextColor(getResources().getColor(R.color.colorText));
                }
                return view;
            }
        };
        adapter2.setDropDownViewResource(R.layout.spinner_item_layout);
        adapter3.setDropDownViewResource(R.layout.spinner_item_layout);
        finish2.setAdapter(adapter2);
        finish3.setAdapter(adapter3);
        finish2.setSelection(0, true);
        finish3.setSelection(0, true);
        finish2.setOnItemSelectedListener(new BaseSpinner() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                loadingHorizontal = showLoadingHorizontal(getApplication(), "正在加载...").show();
                if (i == 0) {
                    year = "";
                } else if (i == 1) {
                    year = "2018";
                } else if (i == 2) {
                    year = "2017";
                } else if (i == 3) {
                    year = "2016";
                }
                if (null != mList && mList.size() > 0) {
                    mList.clear();
                    mAdapter.notifyDataSetChanged();
                }
                if (null != currentId && !currentId.trim().isEmpty() && !currentId.equals("全部单位")) {
                    Logger.e("getData(id)");
                    getMessagesData(currentId);
                } else {
                    getMessagesData(null);
                    Logger.e("getData(null)");
                }
            }

        });
        finish3.setOnItemSelectedListener(new BaseSpinner() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                loadingHorizontal = showLoadingHorizontal(getApplication(), "正在加载...").show();
                if (i == 0) {
                    season = "";
                } else{
                    season = i+"";
                }
                if (null != mList && mList.size() > 0) {
                    mList.clear();
                    mAdapter.notifyDataSetChanged();
                }
                if (null != currentId && !currentId.trim().isEmpty() && !currentId.equals("全部单位")) {
                    getMessagesData(currentId);
                } else {
                    getMessagesData(null);
                }
            }

        });
    }

    private PopupWindow popupWindow;
    private LinkedList<Node> mLinkedList = new LinkedList<>();
    private NodeTreeAdapter nodeTreeAdapter;
    private List<Node> data;

    private void showPopupWindow(View view) {
        if (null != mLinkedList) {
            View contentView = LayoutInflater.from(this).inflate(R.layout.pop_window, null);
            ListView pop_list = contentView.findViewById(R.id.pop_list);
            final TextView pop_name = contentView.findViewById(R.id.pop_name);
            pop_name.setText("当前选择 : " + finish1.getText());
            nodeTreeAdapter = new NodeTreeAdapter(this, pop_list, mLinkedList);
            pop_list.setAdapter(nodeTreeAdapter);
            nodeTreeAdapter.setOnItemClickListener(new NodeTreeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, String id, String name) {
                    currentId = id;
                    if (name.equals("全部单位")) {
                        getMessagesData(null);
                    } else {
                        getMessagesData(id);
                    }
                    finish1.setText(name);
                    if (null != popupWindow) {
                        popupWindow.dismiss();
                    }
                }
            });
            nodeTreeAdapter.notifyDataSetChanged();
            popupWindow = new PopupWindow(contentView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, true);
            popupWindow.setTouchable(true);
            popupWindow.setOutsideTouchable(true);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            popupWindow.showAsDropDown(view);
        } else {
            try {
                Logger.e("mLinkedList.size" + mLinkedList.size());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void addOne(List<Node> data) {
        if (null != companyBean && companyBean.getVo().size() > 0) {
            data.add(new Dept(-1, -1, "全部单位", "全部单位"));
            for (int i = 0; i < companyBean.getVo().size(); i++) {
                Logger.e("i = " + i);
                try {
                    int id = Integer.parseInt(companyBean.getVo().get(i).getId());
                    int pid = Integer.parseInt(companyBean.getVo().get(i).getPId());
                    String name = companyBean.getVo().get(i).getName();
                    String mId = companyBean.getVo().get(i).getId();
                    data.add(new Dept(id, pid, name, mId));
                } catch (Exception e) {
                    Logger.e("exception");
                }
            }
        }
    }

    private void showCommit(String msg) {
        ids=msg.replace("[","").replace("]","").replace(" ","");
        MdAlert = DialogUIUtils.showMdAlert(this, "审核提示", "是否审核选中合同？", new DialogUIListener() {
            @Override
            public void onPositive() {
                loadingHorizontal = showLoadingHorizontal(getApplication(), "审核中...").show();
                String JSESSIONID = getStringData(CaseProcess1.this, "JSESSIONID", "");
                caseProcess1Presenter.shMessage(JSESSIONID, ids,"yes", "批量默认通过");
            }

            @Override
            public void onNegative() {
                MdAlert.dismiss();
            }
        }).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        App.getInstance().getCaseProcess1List().clear();
    }
}